using Abp.Collections.Extensions;
using Abp.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Mt.Site.Application.Dto.Add;
using Mt.Site.Core.Navigations;
using Mt.Site.Core.Navigations.Values;
using Mt.Site.Core.Storage;
using Mt.Site.Core.Url;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

namespace Mt.Site.Web.Helpers
{
    public static class AppExtesions
    {


        /// <summary>
        /// 一次传入多个值，选择第一个不为空的（如取有效的图片alt）
        /// </summary>
        /// <param name="strs"></param>
        /// <returns></returns>
        public static string NotNullAlterName(params string[] strs)
        {
            for (int i = 0; i < strs.Length; i++)
            {
                var item = strs[i];
                if (!string.IsNullOrWhiteSpace(item))
                {
                    return item;
                }
            }

            return "";
        }

        /// <summary>
        /// 字符串用逗号分割后格式化
        /// </summary>
        /// <param name="str"></param>
        /// <param name="separator"></param>
        /// <param name="alterFunc"></param>
        /// <returns></returns>
        public static string ArrStrFormat(string str, string separator, Func<string, string> alterFunc)
        {
            if (str.IsNullOrEmpty())
            {
                return "";
            }
            var arr = str.Split(',');

            string item;
            var html = "";
            for (var i = 0; i < arr.Length; i++)
            {
                item = arr[i];
                if (item.Trim() != "")
                {
                    if (html != "")
                    {
                        html += separator;
                    }
                    if (alterFunc != null)
                    {
                        html += alterFunc(item);
                    }
                    else
                    {
                        html += item;
                    }
                }
            }
            return html;
        }

        public static bool CheckUrlRedirect(HttpContext httpContext, string currentUrl)
        {
            var rawUrl = httpContext.Items["RawAbsolutePath"];
            if(rawUrl != null && rawUrl.ToString() != currentUrl)
            {
                return true;
            }

            return false;
        }

        public static string GetHostName()
        {
            return "https://www.xxx.com";
        }

        public static string GetNoDataHtml()
        {
            var StrNoData = "";
            StrNoData += "<div class=\"nodata\">";
            StrNoData += "<img src=\"/content/img/images/nodata.png\" >";
            StrNoData += "<div class=\"nodataText\">";
            StrNoData += "抱歉，没有找到匹配项。";
            StrNoData += "</div>";
            StrNoData += "</div>";

            return StrNoData;
        }

        private static string getPageUrl(int page, string currentPageUrl)
        {
            if (page == 1)
            {
                return currentPageUrl;
            }
            return currentPageUrl + "/page_" + page;
        }

        public static string GetPageHtml(int maxResultCount, int totalCount, int pageIndex,
            string currentPageUrl)
        {
            if (totalCount == 0)
            {
                return "";
            }

            var remainder = totalCount % maxResultCount;
            var size = totalCount / maxResultCount;
            var pageCount = remainder == 0 ? size : size + 1;
            if (pageCount == 1)
            {
                return "";
            }

            var html = "";
            if (pageIndex > 1)
            {
                html += "<a href=\"" + getPageUrl(pageIndex - 1, currentPageUrl) + "\" class=\"ctrl prev \"><i class=\"icon\"></i></a>";
            }
            else
            {
                html += "<a href=\"javascript:;\" class=\"ctrl prev disabled\"><i class=\"icon\"></i></a>";
            }
            html += "<div class=\"numbox\">";
            for (var i = 1; i <= pageCount; i++)
            {
                if (i == pageIndex)
                {
                    html += "<a href=\"" + getPageUrl(i, currentPageUrl) + "\" class=\"active\"><span>" + i + "</span></a>";
                }
                else
                {
                    html += "<a href=\"" + getPageUrl(i, currentPageUrl) + "\" ><span>" + i + "</span></a>";
                }
            }
            html += "</div>";
            if (pageIndex < pageCount)
            {
                html += "<a href=\"" + getPageUrl(pageIndex + 1, currentPageUrl) + "\" class=\"ctrl next \"><i class=\"icon\"></i></a>";
            }
            else
            {
                html += "<a href=\"javascript:;\" class=\"ctrl next disabled\"><i class=\"icon\"></i></a>";
            }

            return html;
        }


        public static int GetPageIndex(string page)
        {
            int pageIndex = 1;
            if (page.StartsWith("page_", StringComparison.OrdinalIgnoreCase))
            {
                page = page.Substring(5);
                if (int.TryParse(page, out pageIndex) && pageIndex > 0)
                {
                    return pageIndex;
                }
            }

            return pageIndex;
        }




        public static string GetUrl(this MtFrontEndUserMenuItem userMenuItem,IUrlGetter url)
        {
            return _GetUrl(userMenuItem.CustomUrl, userMenuItem.Url,userMenuItem.ActionName,
                userMenuItem.ControllerName,userMenuItem.IsSpecial, url,userMenuItem.KindId);
        }
        public static string GetTarget(this MtFrontEndUserMenuItem userMenuItem)
        {
            return _GetTarget(userMenuItem.Target);
        }
        
        public static string GetUrl(this MenuItemInfo menuInfo, IUrlGetter url)
        {
            return _GetUrl(menuInfo.CustomUrl, menuInfo.Url, menuInfo.ActionName, menuInfo.ControllerName, 
                menuInfo.IsSpecial, url, menuInfo.KindId);
        }
        public static string GetTarget(this MenuItemInfo menuInfo)
        {
            if(!menuInfo.CustomUrl.IsNullOrWhiteSpace())
            {
                return "_blank";
            }
            return _GetTarget(menuInfo.Target);
        }


        public static string GetUrl(this DetailPageInfo page, long kind, IUrlGetter url)
        {
            return _GetUrl(null, page.Url, page.ActionName,
                page.ControllerName, false, url, kind);
        }
        public static string GetTarget(this DetailPageInfo page)
        {
            return _GetTarget(page.Target);
        }

        //--
        private static string _GetUrl(
            string menuCustomUrl,
            string url, string actionName, string controlerName,
            bool isSpecial, IUrlGetter urlGette, long kind)
        {
            if (!menuCustomUrl.IsNullOrWhiteSpace())
            {
                return menuCustomUrl;
            }

            if (!url.IsNullOrWhiteSpace())
            {
                return url;
            }

            if (isSpecial)
            {
                //首页
                if (!actionName.IsNullOrWhiteSpace() && !controlerName.IsNullOrWhiteSpace())
                {
                    return urlGette.Action(
                        actionName,
                        controlerName,
                        new
                        {
                            Area = "",
                            tenancyName = urlGette.TenancyName,
                            cultureName = urlGette.CultureName
                        });
                }
                return urlGette.Action(
                        "Index",
                        "Home",
                        new
                        {
                            Area = "",
                            tenancyName = urlGette.TenancyName,
                            cultureName = urlGette.CultureName
                        });
            }
            else
            {
                if (!actionName.IsNullOrWhiteSpace() && !controlerName.IsNullOrWhiteSpace())
                {
                    int shortKindId = urlGette.ShortIdManager.GetShortId(kind);
                    return urlGette.Action(
                        actionName,
                        controlerName,
                        new
                        {
                            Area = "",
                            tenancyName = urlGette.TenancyName,
                            cultureName = urlGette.CultureName,
                            kind = shortKindId
                        });
                }
                return null;
            }
        }

        private static string _GetTarget(string target)
        {
            if (target.IsNullOrWhiteSpace())
            {
                return "";
            }
            else
            {
                return $" target={target} ";
            }
        }


        
        /// <summary>
        /// 判断当前栏目是否有三级以上栏目
        /// </summary>
        /// <param name="list"></param>
        /// <param name="NowItem"></param>
        /// <returns></returns>
        public static bool IsMoreThanThreeMenu(IList<MtFrontEndUserMenuItem> list,MtFrontEndUserMenuItem NowItem)
        {
            foreach (var item in list)
            {
                if (item.Id == NowItem.Id)
                {
                    foreach (var n in item.Items)
                    {
                        if (n.Items.Count > 0)
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        public static string DisplayImg(this IWebUrlService webUrlService, string p)
        {
            if (p.IsNullOrWhiteSpace())
            {
                return "/content/defaultImg/DefaultImage.jpg";
            }
            if (p.StartsWith(webUrlService.FileServerRootAddress))
            {
                return p;
            }
            return $"{webUrlService.FileServerRootAddress}{p}";
        }

        public static string DisplayImg(this IWebUrlService webUrlService, string p,string DefaultImage)
        {
            //!p.Contains("aliyuncs")
            if (!string.IsNullOrEmpty(p))
            {
                if(p.StartsWith(webUrlService.FileServerRootAddress))
                {
                    return p;
                }
                return $"{webUrlService.FileServerRootAddress}{p}";
            }
            else
            {
                if (!string.IsNullOrEmpty(DefaultImage))
                {
                    if (DefaultImage.StartsWith(webUrlService.FileServerRootAddress))
                    {
                        return DefaultImage;
                    }
                    return $"{webUrlService.FileServerRootAddress}{DefaultImage}";
                }
                return "/content/defaultImg/DefaultImage.jpg";
            }
        }

        public static string DisplayImg(this IWebUrlService webUrlService, string p, int width, int height)
        {
            if (p.IsNullOrWhiteSpace())
            {
                return $"/content/defaultImg/DefaultImage-{width}x{height}.jpg";
            }
            if (p.StartsWith(webUrlService.FileServerRootAddress))
            {
                return p;
            }
            return $"{webUrlService.FileServerRootAddress}{p}";
        }


        public static string GetDetime(long time)
        {
            return time.FromUnixTimestampByMilliseconds().ToLocalTime().ToString("yyyy - MM - dd");
        }

        public static string GetDetimeCn(long time)
        {
            return time.FromUnixTimestampByMilliseconds().ToLocalTime().ToString("yyyy年MM月dd日");
        }

        /// <summary>
        /// 将数据库中的时间以固定格式显示
        /// 传入null或空串时返回null
        /// </summary>
        /// <param name="listtime"></param>
        /// <param name="format">eg:"yyyy-MM-dd HH:mm"</param>
        /// <returns></returns>
        public static string FormatDate(this long listtime, string format)
        {
            if (listtime > 0)
            {
                DateTime? date = listtime.FromUnixTimestampByMilliseconds().ToLocalTime();
                try
                {
                    if (date.HasValue)
                    {
                        return date.Value.ToString(format);
                    }
                }
                catch (Exception) { }
            }
            return null;
        }

        /// <summary>
        /// 转换换行
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string ParseHtml(string p)
        {
            if (!string.IsNullOrEmpty(p))
            {
                p = FilterHtml(p);
                return p.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 转换换行为p标签
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string ParseHtmlP(string p)
        {
            if (!string.IsNullOrEmpty(p))
            {
                //p = FilterHtml(p);
                return p.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                    .Select((t) => $"<p>{t}</p>")
                    .JoinAsString("\r\n");
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 转换换行为span标签
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string ParseHtmlspan(string p)
        {
            if (!string.IsNullOrEmpty(p))
            {
                return p.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                    .Select((t) => $"<span>{t}</span>")
                    .JoinAsString("\r\n");
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// html转移
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string HtmlDecode(this string html)
        {
            if (!html.IsNullOrEmpty())
            {
                string FilterHtmlString = WebUtility.HtmlDecode(html);
                return FilterHtml(FilterHtmlString);
            }
            else
            {
                return "";
            }
        }


        /// <summary>
        /// 提取html中的纯文本
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string GetText(string html)
        {
            if (!string.IsNullOrEmpty(html))
            {
                return Regex.Replace(html, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            }
            return "";
        }

        /// <summary>
        /// 获取文件或图片
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static FileObjectDto GetPicOrFile(this Dictionary<string, FileObjectDto> dic, string key)
        {
            if (dic != null && dic.Count > 0 && !key.IsNullOrEmpty())
            {
                var picOrFile = new FileObjectDto();
                if (!dic.TryGetValue(key, out picOrFile))
                {
                    picOrFile = new FileObjectDto();
                }
                if (picOrFile != null)
                {
                    return picOrFile;
                }
                else
                {
                    return new FileObjectDto();
                }
            }
            else
            {
                return new FileObjectDto();
            }
        }

        private static string FilterHtml(string html)
        {
            html = html.Replace("alert", "");
            html = html.Replace("confirm", "");
            html = html.Replace("prompt", "");
            html = html.Replace("embed", "");
            html = html.Replace("script", "");
            html = html.Replace("base", "");
            html = html.Replace("onload", "");
            html = html.Replace("position", "");
            html = html.Replace("iframe", "");
            html = html.Replace("meta", "");
            html = html.Replace("object", "");
            html = html.Replace("aim.exe", "");
            html = html.Replace("document", "");
            html = html.Replace("onmouseover", "");
            html = html.Replace("write", "");
            html = html.Replace("autofocus", "");
            html = html.Replace("onfocus", "");
            html = html.Replace("onerror", "");
            return html;
        }

        /// <summary>
        /// 获取文件或图片列表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static List<FileObjectDto> GetPicsOrFilesList(this Dictionary<string, List<FileObjectDto>> dic, string key)
        {
            if (dic != null && dic.Count > 0 && !key.IsNullOrEmpty())
            {
                List<FileObjectDto> picsOrFilesList;
                if (!dic.TryGetValue(key, out picsOrFilesList))
                {
                    picsOrFilesList = new List<FileObjectDto>();
                }

                if (picsOrFilesList != null)
                {
                    return picsOrFilesList;
                }
                else
                {
                    return new List<FileObjectDto>();
                }
            }
            else
            {
                return new List<FileObjectDto>();
            }
        }

    }
}
